package com.ajieee.merge.runner.finance.proxy;

import com.ajieee.merge.entity.finance.po.EtfQuotePO;
import com.ajieee.merge.entity.finance.po.TradeDatePO;
import com.ajieee.merge.enums.finance.Adjust;
import com.ajieee.merge.util.DateUtils;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.client.RestClient;
import org.springframework.web.util.UriComponentsBuilder;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ajieee
 * @date 2025-10-02
 */
@Component
@RequiredArgsConstructor
public class AkShareProxy {

	private final RestClient restClient;

	public List<TradeDatePO> getTradeDate() {
		JsonNode root = restClient.get()
				.uri("http://localhost:8080/api/public/tool_trade_date_hist_sina")
				.retrieve()
				.body(JsonNode.class);
		List<TradeDatePO> pos = new ArrayList<>(root.size());
		for (JsonNode node : root) {
			String tradeDate = node.get("trade_date").asText();
			TradeDatePO po = new TradeDatePO();
			po.setTradeDate(DateUtils.parseDate(tradeDate, "yyyy-MM-dd'T'HH:mm:ss.SSS"));
			po.setDateInt(DateUtils.formatDate(po.getTradeDate(), "yyyyMMdd", Integer.class));
			pos.add(po);
		}

		return pos;
	}

	public List<EtfQuotePO> getEtfHistoryQuote(String fundCode, Adjust adjust) {
		String uriString = UriComponentsBuilder.fromUriString("http://localhost:8080/api/public/stock_zh_a_hist")
				.queryParam("symbol", fundCode)
				.queryParam("period", "daily")
				.queryParam("adjust", convertAdjust(adjust))
				.build().encode().toUriString();
		JsonNode root = restClient.get()
				.uri(uriString)
				.retrieve()
				.body(JsonNode.class);
		Assert.notNull(root, "没有数据");

		List<EtfQuotePO> pos = new ArrayList<>(root.size());
		for (JsonNode node : root) {
			EtfQuotePO po = new EtfQuotePO();
			LocalDate dataDate = DateUtils.parseDate(node.get("日期").asText(), "yyyy-MM-dd'T'HH:mm:ss.SSS");
			po.setDataDate(dataDate);
			po.setFundCode(fundCode);
			po.setOpen(node.get("开盘").asDouble());
			po.setClose(node.get("收盘").asDouble());
			po.setHigh(node.get("最高").asDouble());
			po.setLow(node.get("最低").asDouble());
			po.setVolume(node.get("成交量").asDouble() * 100);
			po.setAmount(node.get("成交额").asDouble());
			po.setChange(node.get("涨跌额").asDouble());
			po.setChangeRatio(node.get("涨跌幅").asDouble());
			pos.add(po);
		}
		return pos;
	}

	String convertAdjust(Adjust adjust) {
		return switch (adjust) {
			case PRE_ADJUST -> "qfq";
			case POST_ADJUST -> "hfq";
			default -> "";
		};
	}
}
